//
//  LZSearchViewController.m
//  沙哈拉FM
//
//  Created by dllo on 15/11/11.
//  Copyright © 2015年 S1mpl3. All rights reserved.
//

#import "LZSearchViewController.h"
#import "FitHeader.h"
#import "TabBarController.h"
#import "LZSearchCollectionViewCell.h"
#import "HeadViewButton.h"
#import "TwoToOne.h"
#import "ZBBPlayHistory.h"
#import "LZSearch.h"
#import "MJRefresh.h"
#import "BaseView.h"
#import "MBProgressHUD.h"
#import "LZSearchAlbum.h"
#import "LZSearchAlbumTableViewCell.h"
#import "LZSearchUserTableViewCell.h"
#import "LZSearchTrackTableViewCell.h"
#import "S1mpl3AlbumViewController.h"
#import "S1mpl3HeadInfoViewController.h"
#import "LZPlayViewController.h"
#import "UIImage+GIF.h"

#import "Model.h"

#import "UIImageView+WebCache.h"


@interface LZSearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, strong)UISearchBar *searchBar;
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong)NSArray *array;
@property(nonatomic, strong)NSArray *array1;

@property(nonatomic, strong)NSMutableArray *collectionViewArray;
@property(nonatomic, strong)NSMutableArray *historyArray;

@property(nonatomic, strong)NSString *searchTextString;//searchText
@property(nonatomic, strong)NSMutableArray *dataSourceArray;//tableView的数住
@property(nonatomic, strong)UITableView *tableView;//模糊搜索出来的

@property(nonatomic, strong)UISegmentedControl *segmentController;
@property(nonatomic, strong)BaseView *backView;
@property(nonatomic, strong)UITableView *lastTableView;

@property(nonatomic, strong)MBProgressHUD *progressView;
@property(nonatomic, strong)NSString *coreString;//core进行拼接
@property(nonatomic, strong)NSMutableArray *searchSourceArray;
@property(nonatomic, assign)NSInteger page;

@property(nonatomic, strong)NSMutableArray *searchUserSourceArray;
@property(nonatomic, strong)NSMutableArray *dicTrackArray;

@end
static NSMutableArray *historyArray = nil;
@implementation LZSearchViewController
- (void)viewWillAppear:(BOOL)animated{
    
    //    [[TabBarController shareInstance] totalTabBarShouldHiden:YES];
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(25 * FITWidth, 15 * FITHeight, 325 * FITWidth, 20 * FITHeight)];
    _searchBar.placeholder = @"搜索声音, 专辑, 人名";
    _searchBar.delegate = self;
    [_searchBar setSearchResultsButtonSelected:YES];
    [_searchBar becomeFirstResponder];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar addSubview:_searchBar];
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor redColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[Model shareInstance].TitleColor, NSForegroundColorAttributeName, nil]];
    
    [[TabBarController shareInstance] totalTabBarShouldHiden:NO];
    
//    [[TabBarController shareInstance] remainButtonOfPlay:YES];
//
    [TabBarController shareInstance].myView.backgroundColor = [UIColor whiteColor];
    
    //    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:nil style:UIBarButtonSystemItemDone target:nil action:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    
    
//    [[TabBarController shareInstance] totalTabBarShouldHiden:NO];
//    
//    [[TabBarController shareInstance] remainButtonOfPlay:NO];
    
    _searchBar.hidden = YES;
    
    [_searchBar resignFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self getData];
    
}
- (void)loadView{
    [super loadView];
    _array = @[@"搜索历史", @"热门搜索"];
    _array1 = @[@"清空历史", @""];
    _collectionViewArray = [NSMutableArray array];
    _historyArray = [NSMutableArray array];
    _dataSourceArray = [NSMutableArray array];
    _searchSourceArray = [NSMutableArray array];
    _searchUserSourceArray = [NSMutableArray array];
    _dicTrackArray = [NSMutableArray array];
    
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    //    flowLayout.itemSize = CGSizeMake(80 * FITWidth, 20 * FITHeight);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 20 * FITWidth, 0, 20 * FITWidth);
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[LZSearchCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    
    [_collectionView registerClass:[HeadViewButton class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"identifier1"];
    [self.view addSubview:_collectionView];
    //模糊搜索的
    _tableView = [[UITableView alloc]init];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    _tableView.tableFooterView = [[UIView alloc]init];
    
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    [[[_progressView subviews]firstObject] removeFromSuperview];
    [[[_progressView subviews] objectAtIndex:1] removeFromSuperview];
    [_progressView setMode:0];
    [_progressView show:YES];
    NSString  *name = @"RED.gif";
    _progressView.color = [UIColor clearColor];
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(-70 * FITWidth, -80 * FITHeight, 140 * FITWidth, 100 * FITHeight)];
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 10;
    imageView.opaque = NO;
    
    [[[[[_progressView subviews] lastObject] subviews] firstObject] removeFromSuperview];
    
    imageView.image = [UIImage sd_animatedGIFWithData:imageData];
    [[[_progressView subviews] lastObject] addSubview:imageView];
    [self.view addSubview:_progressView];
    
    _backView = [[BaseView alloc]init];
    _backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_backView];
    
    _segmentController = [[UISegmentedControl alloc]initWithItems:@[@"专辑", @"主播", @"声音"]];
    _segmentController.frame = CGRectMake(5 * FITWidth, 0, (375 - 10) * FITWidth, 30 * FITHeight);
    _segmentController.tintColor = [UIColor redColor];
    [_segmentController addTarget:self action:@selector(segmentOneAction:) forControlEvents:UIControlEventValueChanged];
    [_segmentController setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil] forState:UIControlStateNormal];
    [_backView addSubview:_segmentController];
    [_segmentController setHidden:YES];
    
    //点击进入详情的
    _lastTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30 * FITHeight, 375 * FITWidth, 667 * FITHeight - 64 - 30 * FITHeight) style:UITableViewStylePlain];
    _lastTableView.delegate = self;
    _lastTableView.dataSource = self;
    [_backView addSubview:_lastTableView];
    [_lastTableView setHidden:YES];
    
}
- (void)mjRefreshAction{
    _page = 1;
    [_searchSourceArray removeAllObjects];
//    [_lastTableView.mj_header beginRefreshing];
    [self getThirdData];
    //下拉刷新
    _lastTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_searchSourceArray removeAllObjects];
        _page = 1;
        [self getThirdData];
    }];
    //上拉加载
    _lastTableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        _page++;
        [self getThirdData];
    }];
}
#pragma mark - segment点击方法
- (void)segmentOneAction:(UISegmentedControl *)seg{
    
    if (seg.selectedSegmentIndex == 0) {
        _coreString = @"album";
        [self mjRefreshAction];
    }else if(seg.selectedSegmentIndex == 1){
        _coreString = @"user";
        [self mjRefreshAction];
    }else{
        _coreString = @"track";
        [self mjRefreshAction];
    }
    
}
- (void)getData{
    NSString *urlString = @"http://mobile.ximalaya.com/s/hot_search_key?device=android&size=9";
    [TwoToOne getDataByString:urlString BodyString:nil WithDataBlock:^(id data) {
        NSArray *array = [data objectForKey:@"list"];
        for (NSString *str in array) {
            [_collectionViewArray addObject:str];
        }
        [_collectionView reloadData];
        [_progressView removeFromSuperview];
    }];
}
- (void)getSecondData{
    [_tableView.mj_header endRefreshing];
    [_dataSourceArray removeAllObjects];
    NSString *urlString = [NSString stringWithFormat:@"http://search.ximalaya.com/suggest?device=iPhone&kw=%@", _searchTextString];
    [TwoToOne getDataByString:urlString BodyString:nil WithDataBlock:^(id data) {
        NSArray *array = [data objectForKey:@"albumResultList"];
        NSArray *array1 = [data objectForKey:@"queryResultList"];
        NSMutableArray *dicArray2 = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            LZSearch *search = [[LZSearch alloc]init];
            [search setValuesForKeysWithDictionary:dic];
            [_dataSourceArray addObject:search];
        }
        for (NSDictionary *dic in array1) {
            LZSearch *search = [[LZSearch alloc]init];
            [search setValuesForKeysWithDictionary:dic];
            [dicArray2 addObject:search];
        }
        [_dataSourceArray addObjectsFromArray:dicArray2];
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
        [_progressView removeFromSuperview];
    }];
}
- (void)getThirdData{
//    [_lastTableView.mj_header endRefreshing];
    NSString *urlString = [NSString stringWithFormat:@"http://search.ximalaya.com/front/v1?condition=relation&core=%@&device=iPhone&kw=%@&page=%ld&rows=20", _coreString, _searchTextString, _page];
    [TwoToOne getDataByString:urlString BodyString:nil WithDataBlock:^(id data) {
        NSDictionary *responseDic = [data objectForKey:@"response"];
        NSArray *docsArray = [responseDic objectForKey:@"docs"];
        _dicTrackArray = [NSMutableArray array];
        [_dicTrackArray addObjectsFromArray:docsArray];
        for (NSDictionary *dic in docsArray) {
            LZSearchAlbum *lzSearch = [[LZSearchAlbum alloc]init];
            [lzSearch setValuesForKeysWithDictionary:dic];
            [_searchSourceArray addObject:lzSearch];
        }

        [_lastTableView reloadData];
        [_progressView removeFromSuperview];
        [_lastTableView.mj_header endRefreshing];
        [_lastTableView.mj_footer endRefreshing];
    }];
}
#pragma mark - cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _lastTableView) {
        return _searchSourceArray.count;
    }
    return _dataSourceArray.count;
}
#pragma mark - cell点击跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_searchBar resignFirstResponder];
    
    if (tableView == _lastTableView) {
        if (_segmentController.selectedSegmentIndex == 0) {
            S1mpl3AlbumViewController *simple = [[S1mpl3AlbumViewController alloc]init];
            simple.albumId = [_searchSourceArray[indexPath.row] ID];
            [self.navigationController pushViewController:simple animated:YES];
        }else if (_segmentController.selectedSegmentIndex == 1){
            S1mpl3HeadInfoViewController *simpleHead = [[S1mpl3HeadInfoViewController alloc]init];
            simpleHead.s1mpl3HeadDataSourceDic = _dicTrackArray[indexPath.row];
            [self.navigationController pushViewController:simpleHead animated:YES];
        }else{
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:[LZPlayViewController shareInstance]];
            
            [LZPlayViewController shareInstance].index = indexPath.row;
            [LZPlayViewController shareInstance].dataArray = _searchSourceArray;
            [LZPlayViewController shareInstance].dicArray = _dicTrackArray;
            NSDictionary *dic = _dicTrackArray[indexPath.row];
            [LZPlayViewController shareInstance].dic = dic;
            
            [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"cell0"];
            [self presentViewController:nav animated:YES completion:nil];
            
            [[TabBarController shareInstance].imageView sd_setImageWithURL:[NSURL URLWithString:[_dicTrackArray[indexPath.row] objectForKey:@"album_cover_path"]]];
        }
    }else{
        
        NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *documentPath = [documents stringByAppendingPathComponent:@"LZSearchHistory.txt"];
    
        [_segmentController setHidden:NO];
        [_lastTableView setHidden:NO];
        _backView.frame = CGRectMake(0, 0, 375 * FITWidth, 667 * FITHeight - 64);
        
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        _searchTextString = cell.textLabel.text;
        _searchBar.text = _searchTextString;

        if (_historyArray == nil) {
            NSArray *array = [NSArray arrayWithObjects:cell.textLabel.text, nil];
            [array writeToFile:documentPath atomically:YES];
        }else{

            for (NSString *str in _historyArray) {
                if ([_searchBar.text isEqualToString:str]) {
                    [_searchBar resignFirstResponder];
                    _segmentController.selectedSegmentIndex = 0;
                    [self segmentOneAction:_segmentController];
                    return;
                }
            }
            [_historyArray insertObject:_searchBar.text atIndex:0];
            [_historyArray writeToFile:documentPath atomically:YES];
        }
        
        self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
        [[[_progressView subviews]firstObject] removeFromSuperview];
        [[[_progressView subviews] objectAtIndex:1] removeFromSuperview];
        [_progressView setMode:0];
        [_progressView show:YES];
        NSString  *name = @"RED.gif";
        _progressView.color = [UIColor clearColor];
        NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
        NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(-70 * FITWidth, -80 * FITHeight, 140 * FITWidth, 100 * FITHeight)];
        imageView.layer.masksToBounds = YES;
        imageView.layer.cornerRadius = 10;
        imageView.opaque = NO;
        
        [[[[[_progressView subviews] lastObject] subviews] firstObject] removeFromSuperview];
        
        imageView.image = [UIImage sd_animatedGIFWithData:imageData];
        [[[_progressView subviews] lastObject] addSubview:imageView];
        [self.view addSubview:_progressView];
        [self getSecondData];
        
        _segmentController.selectedSegmentIndex = 0;
        [self segmentOneAction:_segmentController];
        
    }
}

#pragma mark - 查找所有子串的string
- (NSMutableArray *)subString:(NSString *)subString
                     InString:(NSString *)superString{
    NSMutableArray *array = [NSMutableArray array];
    NSString *copyString = superString;
    while ([copyString rangeOfString:subString].location != NSNotFound)
    {
        NSRange  range  = [copyString rangeOfString:subString];
        //        NSLog(@"location:%ld", range.location);
        
        [array addObject:[NSNumber numberWithInteger:range.location]];
        NSMutableString *repleaceString = [NSMutableString string];
        for (NSInteger i = 0; i < subString.length; i++) {
            [repleaceString appendString:@"∫"];
        }
        copyString = [copyString stringByReplacingCharactersInRange:NSMakeRange(range.location, range.length) withString:repleaceString];
    }
    return array;
}
#pragma mark - cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _tableView) {
        static NSString *identifier1 = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier1];
        }
        
        if (_dataSourceArray.count != 0) {
            //关键字标红效果
            NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:[_dataSourceArray[indexPath.row] keyword]];
            //获取关键字的位置
            //        NSRange range = [[_dataSourceArray[indexPath.row] keyword] rangeOfString:_searchTextString];
            
            NSMutableArray *array = [self subString:_searchTextString InString:[_dataSourceArray[indexPath.row] keyword]];
//            NSLog(@"%@", array);
            for (NSNumber *length in array) {
                NSRange range = NSMakeRange([length integerValue], _searchTextString.length);
                //设置关键字属性
                
                [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:20 * FITWidth], NSFontAttributeName, nil] range:range];
                //添加到label
                cell.textLabel.attributedText = attributeString;
            }
            cell.selectionStyle = 0;
            cell.textLabel.text = [NSString stringWithFormat:@"%@", [_dataSourceArray[indexPath.row] keyword]];
            
        }
        return cell;
        
    }else{
        if ([_coreString isEqualToString:@"album"]) {
            
            static NSString *identifier2 = @"cellAlbum";
            LZSearchAlbumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier2];
            if (!cell) {
                cell = [[LZSearchAlbumTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier2];
            }
            cell.selectionStyle = 0;
            [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            if (_searchSourceArray.count != 0) {
                
                cell.lzSearchAlbum = _searchSourceArray[indexPath.row];
            }
            return cell;
        }else if ([_coreString isEqualToString:@"track"]){
            static NSString *identifier3 = @"cellTrack";
            LZSearchTrackTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier3];
            if (!cell) {
                cell = [[LZSearchTrackTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier3];
            }
            cell.selectionStyle = 0;
            if (_dicTrackArray.count > indexPath.row + 1) {
                //                NSLog(@"%ld", indexPath.row);
                cell.dic = _dicTrackArray[indexPath.row];
            }
            return cell;
        }else {
            static NSString *identifier4 = @"cellUser";
            LZSearchUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier4];
            if (!cell) {
                cell = [[LZSearchUserTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier4];
            }
            cell.selectionStyle = 0;
            [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
            if (_searchSourceArray.count != 0) {
                
                cell.lzSearchAlbum = _searchSourceArray[indexPath.row];
            }
            return cell;
        }
    }
}
#pragma mark - 键盘收回
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_searchBar resignFirstResponder];
}
#pragma mark - 当写入数据时
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [_tableView.mj_header beginRefreshing];
    _searchTextString = searchText;
    _page = 1;
    _tableView.frame = CGRectMake(0, 0, 375 * FITWidth, 667 * FITHeight - 64);
    
    [self getSecondData];
    
    //下拉刷新
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_searchSourceArray removeAllObjects];
        [self getSecondData];
    }];
    
    if (searchText.length == 0) {
        _tableView.frame = CGRectMake(0, -603 * FITHeight, 375 * FITWidth, 667 * FITHeight - 64);
        _backView.frame = CGRectMake(0, -603 * FITHeight, 375 * FITWidth, 667 * FITHeight - 64);
        [_collectionView reloadData];
    }
    
}

#pragma mark - 搜索按钮被按下所执行的数据
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    //    NSLog( @"------%@", searchBar.text);
    
    NSString *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *documentPath = [documents stringByAppendingPathComponent:@"LZSearchHistory.txt"];
    
    [_segmentController setHidden:NO];
    [_lastTableView setHidden:NO];
    _backView.frame = CGRectMake(0, 0, 375 * FITWidth, 667 * FITHeight - 64);
    
    if (_historyArray == nil) {
        NSArray *array = [NSArray arrayWithObjects:searchBar.text, nil];
        [array writeToFile:documentPath atomically:YES];
    }else{
        
        for (NSString *str in _historyArray) {
            if ([searchBar.text isEqualToString:str]) {
                [_searchBar resignFirstResponder];
                return;
            }
        }
        [_historyArray insertObject:searchBar.text atIndex:0];
        [_historyArray writeToFile:documentPath atomically:YES];
    }
    
    [_collectionView reloadData];
    [_searchBar resignFirstResponder];
    [self getThirdData];
    
}
#pragma mark - item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documents = [array lastObject];
        NSString *documentPath = [documents stringByAppendingPathComponent:@"LZSearchHistory.txt"];
        _historyArray = [NSMutableArray arrayWithContentsOfFile:documentPath];
        
        return _historyArray.count;
    }
    return _collectionViewArray.count;
}
#pragma mark - cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _lastTableView) {
        if ([_coreString isEqualToString:@"album"]) {
            return 120 * FITHeight;
        }else if ([_coreString isEqualToString:@"track"]){
            return 100 * FITHeight;
        }
        return 80 * FITHeight;
    }
    return 44 * FITHeight;
}
#pragma mark - cell的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    LZSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
    if (indexPath.section == 1) {
        cell.string = _collectionViewArray[indexPath.row];
        return cell;
    }else{
        cell.string = [NSString stringWithFormat:@"%@", _historyArray[indexPath.row]];
        return cell;
    }
}
#pragma mark - collection点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [_searchBar resignFirstResponder];
    
    [_segmentController setHidden:NO];
    [_lastTableView setHidden:NO];
    
    _backView.frame = CGRectMake(0, 0, 375 * FITWidth, 667 * FITHeight - 64);
    
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    [[[_progressView subviews]firstObject] removeFromSuperview];
    [[[_progressView subviews] objectAtIndex:1] removeFromSuperview];
    [_progressView setMode:0];
    [_progressView show:YES];
    NSString  *name = @"RED.gif";
    _progressView.color = [UIColor clearColor];
    NSString  *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData  *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(-70 * FITWidth, -80 * FITHeight, 140 * FITWidth, 100 * FITHeight)];
    imageView.layer.masksToBounds = YES;
    imageView.layer.cornerRadius = 10;
    imageView.opaque = NO;
    
    [[[[[_progressView subviews] lastObject] subviews] firstObject] removeFromSuperview];
    
    imageView.image = [UIImage sd_animatedGIFWithData:imageData];
    [[[_progressView subviews] lastObject] addSubview:imageView];
    [self.view addSubview:_progressView];
    
    LZSearchCollectionViewCell *cell = (LZSearchCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    _searchTextString = cell.nicknameLabel.text;
    _searchBar.text = _searchTextString;
    [self getSecondData];
    
    _segmentController.selectedSegmentIndex = 0;
    [self segmentOneAction:_segmentController];
    
}
#pragma mark collectionView中cell的自适应宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //return CGSizeMake([_collectionViewArray[indexPath.row] length] * 15, 40 * FITHeight);
    if (indexPath.section == 1) {
        
        CGRect rect = [_collectionViewArray[indexPath.row] boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 40 * FITHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil] context:nil];
        return CGSizeMake(ceill(rect.size.width + 1) + 15 * FITWidth, 40 * FITHeight);
    }
    CGRect rect = [_historyArray[indexPath.row] boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 40 * FITHeight) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil] context:nil];
    return CGSizeMake(ceill(rect.size.width + 1) + 15 * FITWidth, 40 * FITHeight);
}

#pragma mark - section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return _array.count;
}
#pragma mark - section的高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.view.frame.size.width, 40 * FITHeight);
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    HeadViewButton *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"identifier1" forIndexPath:indexPath];
    
    //    [headView.leftButton setTitle:[_dataArray[indexPath.section] title] forState:UIControlStateNormal];
    
    [headView.leftButton setTitle:_array[indexPath.section] forState:UIControlStateNormal];
    
    [headView.moreButton setTitle:_array1[indexPath.section] forState:UIControlStateNormal];
    if ([headView.moreButton .titleLabel.text isEqualToString:@"清空历史"]) {
        [headView.moreButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [headView.moreButton addTarget:self action:@selector(clearhistoryAction) forControlEvents:UIControlEventTouchUpInside];
    }
    headView.moreImageView.image = nil;
    
    return headView;
}
- (void)clearhistoryAction{
    [[ZBBPlayHistory shareInstance] removeHistory:@"LZSearchHistory.txt"];
    //[_historyArray removeAllObjects];
    NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [array lastObject];
    NSString *documentPath = [documents stringByAppendingPathComponent:@"LZSearchHistory.txt"];
    _historyArray = [NSMutableArray arrayWithContentsOfFile:documentPath];
    [_collectionView reloadData];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
